import { ref, computed } from 'vue';
import { useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { getImageService } from '@/api/file.js';
import { getUserSpaceService } from '@/api/user.js';

// 静态导入图标资源
import videoIcon from '@/assets/icon-image/video.png';
import musicIcon from '@/assets/icon-image/music.png';
import imageIcon from '@/assets/icon-image/image.png';
import txtIcon from '@/assets/icon-image/txt.png';
import zipIcon from '@/assets/icon-image/zip.png';
import othersIcon from '@/assets/icon-image/others.png';
// 特殊文件类型图标
import codeIcon from '@/assets/icon-image/code.png';
import excelIcon from '@/assets/icon-image/excel.png';
import wordIcon from '@/assets/icon-image/word.png';
import pdfIcon from '@/assets/icon-image/pdf.png';
import pptIcon from '@/assets/icon-image/ppt1.png';
import exeIcon from '@/assets/icon-image/exe.png';

/**
 * 文件列表通用逻辑
 * @param {Object} options 配置选项
 * @param {Function} options.loadDataService 加载数据的服务函数
 * @param {Object} options.categoryNames 分类名称映射
 * @param {Object} options.defaultParams 默认请求参数
 * @returns {Object} 返回响应式数据和方法
 */
export function useFileList(options = {}) {
    const route = useRoute();

    // 基础响应式数据
    const fileList = ref([]);
    const currentPage = ref(1);
    const pageSize = ref(10);
    const total = ref(0);
    const searchName = ref('');
    const selectedFiles = ref([]);
    const isAllSelected = ref(false);
    const isIndeterminate = ref(false);

    // 预览相关
    const previewDialogVisible = ref(false);
    const currentPreviewFile = ref(null);

    // 重命名相关
    const renameDialogVisible = ref(false);
    const newFileName = ref('');
    const currentFile = ref(null);

    // 配置项
    const {
        loadDataService,
        categoryNames = {
            'all': '全部',
            'video': '视频',
            'music': '音频',
            'image': '图片',
            'doc': '文档',
            'zip': '压缩包',
            'others': '其他'
        },
        defaultParams = {}
    } = options;

    // 根据路由参数获取当前分类
    const currentCategory = computed(() => {
        return route.params.category || 'all';
    });

    // 获取当前分类名称
    const currentCategoryName = computed(() => {
        return categoryNames[currentCategory.value] || '全部';
    });

    // 获取分类ID
    const getCategoryId = (category) => {
        const categoryMap = {
            'video': 1,
            'music': 2,
            'image': 3,
            'doc': 4,
            'zip': 5,
            'others': 6
        };
        return categoryMap[category] || null;
    };

    // 根据文件扩展名获取特殊图标
    const getIconByFileExtension = (fileName) => {
        if (!fileName) return null;

        const ext = fileName.toLowerCase().split('.').pop();

        // 代码文件扩展名
        const codeExtensions = ['js', 'ts', 'vue', 'jsx', 'tsx', 'java', 'cpp', 'c', 'h', 'hpp', 'py', 'go', 'php', 'rb', 'cs', 'swift', 'kt', 'scala', 'rs', 'dart', 'lua', 'r', 'sql', 'html', 'css', 'scss', 'sass', 'less', 'xml', 'json', 'yaml', 'yml', 'toml', 'ini', 'cfg', 'conf', 'sh', 'bat', 'ps1', 'dockerfile', 'makefile', 'cmake', 'gradle', 'maven', 'npm', 'package', 'lock'];

        // Excel文件扩展名
        const excelExtensions = ['xls', 'xlsx', 'xlsm', 'xlsb', 'xlt', 'xltx', 'xltm', 'csv'];

        // Word文件扩展名
        const wordExtensions = ['doc', 'docx', 'docm', 'dot', 'dotx', 'dotm', 'rtf'];

        // PowerPoint文件扩展名
        const pptExtensions = ['ppt', 'pptx', 'pptm', 'pot', 'potx', 'potm', 'pps', 'ppsx', 'ppsm'];

        if (codeExtensions.includes(ext)) {
            return codeIcon;
        } else if (excelExtensions.includes(ext)) {
            return excelIcon;
        } else if (wordExtensions.includes(ext)) {
            return wordIcon;
        } else if (ext === 'pdf') {
            return pdfIcon;
        } else if (pptExtensions.includes(ext)) {
            return pptIcon;
        } else if (ext === 'exe' || ext === 'msi') {
            return exeIcon;
        }

        return null;
    };

    // 根据分类获取默认封面
    const getDefaultCoverByCategory = (categoryId) => {
        const coverMap = {
            1: videoIcon,
            2: musicIcon,
            3: imageIcon,
            4: txtIcon,
            5: zipIcon,
            6: othersIcon
        };
        return coverMap[categoryId] || othersIcon;
    };

    // 获取文件图标（优先使用特殊图标，否则使用分类图标）
    const getFileIcon = (file) => {
        const fileName = file.fileName || file.name;
        const specialIcon = getIconByFileExtension(fileName);

        if (specialIcon) {
            return specialIcon;
        }

        return getDefaultCoverByCategory(file.categoryId);
    };

    // 格式化文件大小
    const formatFileSize = (size) => {
        if (!size) return '0 B';

        const units = ['B', 'KB', 'MB', 'GB', 'TB'];
        let index = 0;
        let fileSize = size;

        while (fileSize >= 1024 && index < units.length - 1) {
            fileSize /= 1024;
            index++;
        }

        return `${fileSize.toFixed(2)} ${units[index]}`;
    };

    // 格式化日期时间
    const formatDateTime = (dateTime) => {
        if (!dateTime) return '';

        const date = new Date(dateTime);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');

        return `${year}-${month}-${day} ${hours}:${minutes}`;
    };

    // 加载文件列表
    const loadFileList = async () => {
        if (!loadDataService) {
            console.error('loadDataService is required');
            return;
        }

        try {
            const params = {
                pageNum: currentPage.value,
                pageSize: pageSize.value,
                ...defaultParams
            };

            // 添加分类ID筛选
            const categoryId = getCategoryId(currentCategory.value);
            if (categoryId) {
                params.categoryId = categoryId;
            }

            // 添加搜索条件
            if (searchName.value) {
                params.name = searchName.value;
            }

            const result = await loadDataService(params);
            if (result && result.data) {
                // 为文件列表添加 selected 属性并初始化 imageUrl
                const filesWithSelected = (result.data.records || []).map(file => ({
                    ...file,
                    selected: false,
                    name: file.fileName || file.name || '未命名文件',
                    imageUrl: null // 初始化 imageUrl
                }));

                fileList.value = filesWithSelected;
                total.value = result.data.total || 0;
                selectedFiles.value = []; // 清空选择

                // 重置全选状态
                isAllSelected.value = false;
                isIndeterminate.value = false;

                // 异步为图片文件获取封面
                fileList.value.forEach(async (file) => {
                    if (file.categoryId === 3) {
                        try {
                            const fileId = file.fileId || file.id;
                            const response = await getImageService(fileId);
                            // 当 responseType 为 'blob' 时，数据在 response.data 中
                            if (response.data instanceof Blob) {
                                file.imageUrl = URL.createObjectURL(response.data);
                            }
                        } catch (error) {
                            console.error(`获取文件 ${file.name} 的封面失败:`, error);
                        }
                    }
                });
            }
        } catch (error) {
            console.error('加载文件列表失败:', error);
            ElMessage.error('加载文件列表失败');
        }
    };

    // 分页大小变化
    const handleSizeChange = (val) => {
        pageSize.value = val;
        loadFileList();
    };

    // 页码变化
    const handleCurrentChange = (val) => {
        currentPage.value = val;
        loadFileList();
    };

    // 搜索文件
    const searchFiles = () => {
        currentPage.value = 1; // 搜索时重置页码
        loadFileList();
    };

    // 刷新文件列表
    const refreshFileList = () => {
        loadFileList();
    };

    // 更新已选文件列表
    const updateSelectedFiles = () => {
        selectedFiles.value = fileList.value.filter(file => file.selected);
    };

    // 更新全选状态
    const updateSelectAllStatus = () => {
        const selectedCount = fileList.value.filter(file => file.selected).length;
        const totalCount = fileList.value.length;

        if (selectedCount === 0) {
            isAllSelected.value = false;
            isIndeterminate.value = false;
        } else if (selectedCount === totalCount) {
            isAllSelected.value = true;
            isIndeterminate.value = false;
        } else {
            isAllSelected.value = false;
            isIndeterminate.value = true;
        }

        updateSelectedFiles();
    };

    // 处理全选
    const handleSelectAll = (value) => {
        fileList.value.forEach(file => {
            file.selected = value;
        });
        updateSelectAllStatus();
    };

    // 切换选择状态
    const toggleSelect = (file) => {
        file.selected = !file.selected;
        updateSelectAllStatus();
    };

    // 处理表格行点击事件
    const handleRowClick = (row, column, event) => {
        // 如果点击的是选择框列或操作列，不触发选择
        if (column.property === undefined || column.label === '操作') {
            return;
        }
        // 否则切换选择状态
        toggleSelect(row);
    };

    // 文件预览功能
    const previewFileFunc = async (file) => {
        // 为分享页面适配，确保使用正确的文件ID
        const previewFile = {
            ...file,
            id: file.fileId || file.id,
            name: file.fileName || file.name
        };
        currentPreviewFile.value = previewFile;
        previewDialogVisible.value = true;
    };

    // 下载文件通用逻辑
    const downloadFile = async (file, downloadService) => {
        if (!downloadService) {
            console.error('downloadService is required');
            return;
        }

        try {
            // 确保使用正确的文件ID
            const fileId = file.fileId || file.id;
            const response = await downloadService(fileId);

            // 从响应头获取文件类型，如果没有则使用默认值
            let contentType = response.headers['content-type'] || 'application/octet-stream';

            // 创建正确类型的Blob对象
            const blob = new Blob([response.data], { type: contentType });

            // 创建下载链接
            const link = document.createElement('a');
            link.href = URL.createObjectURL(blob);

            // 设置下载文件名，确保中文文件名正确显示
            const fileName = encodeURIComponent(file.name || file.fileName);
            link.download = decodeURIComponent(fileName);

            // 确保文件名在不同浏览器中都能正确显示
            link.setAttribute('download', decodeURIComponent(fileName));

            link.style.display = 'none'; // 隐藏链接
            document.body.appendChild(link);
            link.click();

            // 清理
            setTimeout(() => {
                document.body.removeChild(link);
                URL.revokeObjectURL(link.href);
            }, 100);
        } catch (error) {
            console.error('下载文件失败:', error);
            ElMessage.error('下载文件失败');
        }
    };

    // 重命名文件
    const renameFile = (file) => {
        currentFile.value = file;
        newFileName.value = file.name || file.fileName;
        renameDialogVisible.value = true;
    };

    // 确认重命名
    const confirmRename = async (renameService) => {
        if (!renameService) {
            console.error('renameService is required');
            return;
        }

        if (!newFileName.value) {
            ElMessage.warning('文件名不能为空');
            return;
        }

        try {
            await renameService({
                id: currentFile.value.id,
                name: newFileName.value
            });

            ElMessage.success('重命名成功');
            renameDialogVisible.value = false;
            loadFileList(); // 刷新文件列表
        } catch (error) {
            console.error('重命名失败:', error);
            ElMessage.error('重命名失败');
        }
    };

    // 路由变化监听
    const watchCategoryChange = (watchFn) => {
        return watchFn(() => route.params.category, () => {
            currentPage.value = 1; // 切换分类时重置页码
            loadFileList();
        });
    };

    return {
        // 响应式数据
        fileList,
        currentPage,
        pageSize,
        total,
        searchName,
        selectedFiles,
        isAllSelected,
        isIndeterminate,
        previewDialogVisible,
        currentPreviewFile,
        renameDialogVisible,
        newFileName,
        currentFile,

        // 计算属性
        currentCategory,
        currentCategoryName,

        // 方法
        getCategoryId,
        getDefaultCoverByCategory,
        getIconByFileExtension,
        getFileIcon,
        formatFileSize,
        formatDateTime,
        loadFileList,
        handleSizeChange,
        handleCurrentChange,
        searchFiles,
        refreshFileList,
        updateSelectedFiles,
        updateSelectAllStatus,
        handleSelectAll,
        toggleSelect,
        handleRowClick,
        previewFileFunc,
        downloadFile,
        renameFile,
        confirmRename,
        watchCategoryChange
    };
}

// 复制文本到剪贴板的通用方法
export const copyText = async (text) => {
    try {
        // 优先使用现代API
        if (navigator.clipboard && window.isSecureContext) {
            await navigator.clipboard.writeText(text);
            ElMessage.success('复制成功');
            return;
        }

        // 降级到传统方案
        const textArea = document.createElement('textarea');
        textArea.value = text;
        textArea.style.position = 'fixed';
        textArea.style.left = '-999999px';
        textArea.style.top = '-999999px';
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();

        return new Promise((resolve, reject) => {
            if (document.execCommand('copy')) {
                ElMessage.success('复制成功');
                resolve();
            } else {
                ElMessage.error('复制失败');
                reject(new Error('复制失败'));
            }
            document.body.removeChild(textArea);
        });
    } catch (error) {
        console.error('复制失败:', error);
        ElMessage.error('复制失败，请手动复制');
    }
};

/**
 * 用户空间管理通用逻辑
 * @returns {Object} 返回用户空间相关的响应式数据和方法
 */
export function useUserSpace() {
    // 用户空间数据
    const userSpace = ref({
        useSpace: 0,
        totalSpace: 1
    });

    // 获取用户空间使用情况
    const getUseSpace = async () => {
        try {
            const result = await getUserSpaceService();
            if (result && result.data) {
                userSpace.value.useSpace = result.data.usedSpace;
                userSpace.value.totalSpace = result.data.totalSpace;
            }
        } catch (error) {
            console.error('获取用户空间信息失败:', error);
            ElMessage.error('获取用户空间信息失败');
        }
    };

    // 计算空间使用百分比
    const spacePercentage = computed(() => {
        return Math.floor(userSpace.value.useSpace / userSpace.value.totalSpace * 100) || 0;
    });

    // 格式化空间大小显示
    const formatSpaceText = computed(() => {
        const usedMB = userSpace.value.useSpace ? (userSpace.value.useSpace / 1024 / 1024).toFixed(2) : 0;
        const totalMB = (userSpace.value.totalSpace / 1024 / 1024).toFixed(0);
        return `${usedMB}MB / ${totalMB}MB`;
    });

    return {
        // 响应式数据
        userSpace,

        // 计算属性
        spacePercentage,
        formatSpaceText,

        // 方法
        getUseSpace
    };
}